package com.icloud.common.web.util;


import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.StrUtil;
import com.icloud.common.core.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

@Component
@Slf4j
public class I18nUtil {
    private static HttpServletRequest httpServletRequest;
    private static final String projectPath = System.getProperty("user.dir") + "\\icloud-common\\icloud-common-web";
    public I18nUtil(HttpServletRequest httpServletRequest) {
        I18nUtil.httpServletRequest = httpServletRequest;
    }

    /**
     * 根据关键字获取对应语言的翻译结果
     * @param code 关键字信息 （本项目对应 module_code + _ + keyword）
     */
    public static String getMessageResult(String code) {
        Locale locale = getCurrentLocale(httpServletRequest.getHeader(CommonConstant.LANGUAGE_REQUEST_HEADER_KEY));
        Map<String, String> propMap = getI18nCacheMap(locale.toString());
        if (!ObjectUtils.isEmpty(propMap) && propMap.containsKey(code)) {
            //如果对应语言中能匹配到数据项，那么直接返回
            return propMap.get(code);
        }
        // 如果找不到国际化消息,就直接返回code
        return code;
    }

    /**
     * 根据当前地域获取对应文件翻译数据
     * @param localeString 地域信息
     */
    public static Map<String, String> getI18nCacheMap(String localeString) {
        Map<String, String> i18nMessageMap = new HashMap<>();
        //读取文件数据
        InputStream inputStream;
        //读取多语言文件内容
        ClassPathResource classPathResource = new ClassPathResource("message_" + localeString + ".properties");
        inputStream = classPathResource.getStream();

        try {
            if(inputStream == null) {
                String url = projectPath.concat("/src/main/resources/message_" + localeString + ".properties");
                inputStream = Files.newInputStream(Paths.get(url));
            }
            Properties properties = new Properties();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            properties.load(bufferedReader);
            Set<Object> keySets = properties.keySet();
            Iterator<Object> iterator = keySets.iterator();
            while (iterator.hasNext()){
                Object obj = iterator.next();
                i18nMessageMap.put(obj.toString(), properties.get(obj).toString());
            }
//            log.info("语言文件map:{}", i18nMessageMap);
            inputStream.close();
        } catch (Exception ignored) {

        }
        return i18nMessageMap;
    }

    /**
     * 获取当前的地域信息
     */
    public static Locale getCurrentLocale(String localeValue) {
        Locale locale = new Locale("zh", "CN");
        if(StrUtil.isNotBlank(localeValue) && StrUtil.contains(localeValue, "-")) {
            String[] strings = localeValue.split("-");
            locale = new Locale(strings[0], strings[1].toUpperCase());
        }
        return locale;
    }
}
